﻿// VsErrorSink.cs
//
// Copyright 2009 by Burt Harris
// Licensed under the Microsoft Public License (Ms-PL)
// See: http://www.codeplex.com/yaml/license
//
using Microsoft.Scripting;
using Microsoft.VisualStudio.Package;
using Microsoft.VisualStudio.TextManager.Interop;
using Severity = Microsoft.Scripting.Severity;

namespace YaTools.Yaml.LanguagePackage
{
    internal class VsErrorSink : ErrorSink
    {
        private readonly AuthoringSink _authoringSink;
        private readonly string _path;

        public VsErrorSink(AuthoringSink authoringSink, string path)
        {
            _authoringSink = authoringSink;
            _path = path;
        }

        public override void Add(string message, string path, string code, string line, SourceSpan span, int errorCode,
                                 Severity severity)
        {
            _authoringSink.AddError(_path, message, TextSpan(span), ConvertSeverity(severity));
        }

        private static Microsoft.VisualStudio.Package.Severity
            ConvertSeverity(Severity input)
        {
            switch (input)
            {
                case Severity.FatalError:
                    return Microsoft.VisualStudio.Package.Severity.Fatal;
                case Severity.Error:
                    return Microsoft.VisualStudio.Package.Severity.Error;
                case Severity.Warning:
                    return Microsoft.VisualStudio.Package.Severity.Warning;
                case Severity.Ignore:
                    return Microsoft.VisualStudio.Package.Severity.Hint;
                default:
                    return Microsoft.VisualStudio.Package.Severity.Error;
            }
        }

        private static TextSpan TextSpan(SourceSpan span)
        {
            var value = new TextSpan();
            value.iStartLine = span.Start.Line - 1;
            value.iEndLine = span.End.Line - 1;
            value.iStartIndex = span.Start.Column - 1;
            value.iEndIndex = span.End.Column - 1;
            return value;
        }
    }
}